package com.lyl.docker.controller;


import cn.hutool.core.util.RandomUtil;
import com.lyl.docker.entity.User;
import com.lyl.docker.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2022-12-10 16:45:23
 */
@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;
    private final RedisTemplate<String, Object> redisTemplate;
    public static final String USER_CACHE = "user:cache:";

    @GetMapping("/add/{num}")
    public boolean addUser(@PathVariable Integer num) {
        log.info("方法名: addUser() , 参数值: num = [" + num + "]");
        List<User> userList = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            userList.add(User.builder()
                    .name(RandomUtil.randomString(5))
                    .sex(RandomUtil.randomInt(0, 1))
                    .build());
        }
        return userService.saveBatch(userList);
    }

    @GetMapping("/list")
    public List<User> list() {
        return userService.list();
    }

    @GetMapping("/{id}")
    public User getById(@PathVariable Integer id) {
        log.info("方法名: getById() , 参数值: id = [" + id + "]");
        User user = (User) redisTemplate.opsForValue().get(USER_CACHE + id);
        if (user == null) {
            user = userService.getById(id);
            log.info("数据放入缓存：id = {}, user = {}", id, user);
            redisTemplate.opsForValue().set(USER_CACHE + id, user);
        }
        return user;
    }

}
